
package com.aiYouPms.admin.controller;

import com.aiYouPms.admin.model.User;
import com.aiYouPms.admin.service.UserService;

import com.aiYouPms.common.api.HttpResult;
import com.aiYouPms.common.api.PageResult;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/users")
public class UserController {


    private final UserService userService;

    public UserController(UserService userService1) {
        this.userService = userService1;
    }


    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/getUserById")
    public  HttpResult<User> getUserById(@RequestParam Long id) {
        return  HttpResult.success(userService.findById(id));
    }

    @GetMapping("/search")
    public  HttpResult<PageResult<User>> search(
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum
    ) {

        PageInfo<User> pageInfo = userService.search(pageSize, pageNum);
        PageResult<User> pageResult = PageResult.of(pageInfo.getList(), pageInfo.getTotal(), pageNum, pageSize);
        return HttpResult.success(pageResult);
    }

    @PostMapping
    public HttpResult<User> createUser(@RequestBody User user) {
        userService.save(user);
        return HttpResult.success(user);
    }

    @PostMapping("/create")
    public User updateUser( @RequestBody User user) {
        user.setId(user.getId());
        userService.save(user);
        return user;
    }

    @DeleteMapping("/delete")
    public String deleteUser(@RequestBody Long id) {
        userService.deleteById(id);
        return "User deleted successfully";
    }
}